package com.xdjd.mobile.business.util;

import com.gitee.easyopen.exception.ApiException;
import net.oschina.durcframework.easymybatis.PageInfo;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class PageInfoUtil {

	public static <T> PageInfo<T> buildPageInfo(PageInfo<?> pageInfo, Class<T> retPojoClass) {
		List<?> list = pageInfo.getList();
		List<T> retList = new ArrayList<>(list.size());
		for (Object obj : list) {
			try {
				T resp = retPojoClass.newInstance();
				BeanUtils.copyProperties(obj, resp);
				retList.add(resp);
			} catch (Exception e) {
				continue;
			}
		}

		PageInfo<T> retPageInfo = new PageInfo<>();
		BeanUtils.copyProperties(pageInfo, retPageInfo);
		retPageInfo.setList(retList);

		return retPageInfo;
	}

	/**
	 * 拷贝一个PageInfo,替换List里面的元素
	 * 
	 * @param pageInfo
	 * @param retPojoClass
	 *            List里面的新元素
	 * @return 返回新的PageInfo
	 */
	public static <T> PageInfo<T> copyPageInfo(PageInfo<?> pageInfo, Class<T> retPojoClass) {
		List<?> list = pageInfo.getList();
		List<T> retList = new ArrayList<>(list.size());
		for (Object obj : list) {
			try {
				T resp = retPojoClass.newInstance();
				BeanUtils.copyProperties(obj, resp);
				retList.add(resp);
			} catch (Exception e) {
				throw new ApiException("拷贝失败");
			}
		}

		PageInfo<T> retPageInfo = new PageInfo<>();
		BeanUtils.copyProperties(pageInfo, retPageInfo);
		retPageInfo.setList(retList);

		return retPageInfo;
	}

}
